{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(size_layer = size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer, reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.LuongMonotonicAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse=reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_out = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_out,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_out = tf.concat((out_fw, out_bw), 2)\n",
    "        bi_state = tf.concat((state_fw,state_bw), -1)\n",
    "        encoder_state = tuple([bi_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-ee1038269df4>:12: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-ee1038269df4>:40: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-ee1038269df4>:19: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[ 4806,  4806,  7844, 17749,  7844,  7844,  7844,  7844,  8016,\n",
       "         16931, 16931, 16931, 10817, 28564, 28564, 28564, 28564, 28564,\n",
       "         28564, 28564, 15376, 15376, 15376, 15376, 12176, 12176, 12176,\n",
       "         12176, 12176, 21343, 21343, 21343, 21343, 21343, 21343, 16575,\n",
       "         16575, 16575, 16575, 16575, 16575, 16575, 16575, 12224, 31957,\n",
       "         16715, 16715, 20056, 20056, 20056, 20056, 20056, 20056, 20056,\n",
       "         21818, 21818,  8402, 19629, 19629, 19629, 19629, 19629, 13732,\n",
       "         19629,   900, 19629,   900, 19629,   900, 18836, 18836, 18836],\n",
       "        [17250, 17250,  9385,  9385,  9385,  9385,   529, 22489, 22489,\n",
       "         22489, 22489, 22489, 22489, 22489, 29215, 29215,   333,   333,\n",
       "           333,   333, 10683, 10683, 10683, 10683, 18647, 18647, 18647,\n",
       "         18647, 18513, 18513, 18513, 18513, 18513, 18513, 18513,  3031,\n",
       "          3031,  3031,  3031,  8819,  8819,  8819, 19052, 27120, 27120,\n",
       "         27120, 27120, 27120, 19378, 20033, 20033, 20033, 20033, 20033,\n",
       "         20033,  7215, 21854,  7215, 21854, 19466, 19466, 28978, 28978,\n",
       "         28978, 23529,  8934,  8934,  8934, 21479, 21479, 21479, 21479],\n",
       "        [ 4953,  4953,  4953,   539,   539, 19389, 19389, 19389, 19389,\n",
       "         19389, 19389, 20751, 26159, 26159, 26159, 26159, 30993, 26159,\n",
       "         30993, 30993, 26159, 24110, 24110, 24110, 24110, 16273, 16273,\n",
       "         16273, 24921, 24921, 27902, 27902,  5450,  5450, 24918, 24918,\n",
       "         24918, 24918, 12684,  5245,  5245,  5245,  5245, 21501, 21501,\n",
       "         21501, 30324, 30324, 30324,  4791, 23984, 23984, 23984, 23984,\n",
       "         23984, 23984, 20529, 17426, 20147, 20147, 20147, 20147, 20147,\n",
       "         20147, 20147, 20147, 20147, 24958, 24958, 24958, 24958,  4406],\n",
       "        [ 4847, 27272, 27272, 27272, 31588, 31588, 31588, 31588, 31588,\n",
       "         31588, 31588, 19436, 19436, 24607, 24607, 24607,  3090,  3090,\n",
       "         30108,  3090,  3090,  3090, 16464, 16464, 16464, 16464, 27971,\n",
       "         27971, 27971, 27971, 31822, 31822, 31822, 24278,  9134,  9134,\n",
       "          9134,  9134, 13251, 12523, 12523, 12523, 12523, 12523,  6067,\n",
       "          6067,  6067,  6067,  2386, 25595, 25595, 25595, 24587, 24587,\n",
       "         11974, 15848, 15848, 15848, 15848, 15848, 15848,  4196,  4196,\n",
       "          4196, 15562,  6785,  6785,  6785,  6785,  6785, 19757, 25325],\n",
       "        [29951, 29951, 10151, 10151, 23033, 23033, 23033, 23033, 23033,\n",
       "         23033, 23033, 23033, 23033, 23033, 23033, 23033, 23033, 23033,\n",
       "         23033, 23033, 23033, 23033, 23033, 22353, 23033, 12606, 23033,\n",
       "         12606, 23033,  9314,  9314,  9314,  8512,  8512,  8512,  8512,\n",
       "         18743, 18743, 18743, 12910, 12910, 10512, 10512, 10512, 10512,\n",
       "         10512, 10512, 10512, 10512, 10512, 10512, 10512, 10512,  6653,\n",
       "          6653,  6653,  6653,  6653,  6653,  6653,  6081,  6081,  3562,\n",
       "          2542,  2542,  2542,  2542,  2542,  2542,  2542, 11756, 11756],\n",
       "        [14603, 11412, 11412, 11412, 11412, 24982, 24982, 24982, 25475,\n",
       "         25475, 25475, 15962, 15962, 15962,  1245,  1245,   100,   100,\n",
       "           100,   100,  1030,  1030,  1030,  1030,  1030,  1030,  1030,\n",
       "         23691, 23691, 23691, 23691, 23691, 23691, 13918, 17390, 17390,\n",
       "         17390, 17390, 20359, 20359, 20359, 20359, 20359, 20359, 20359,\n",
       "         15511, 12559, 12559, 12559, 12559, 12559, 12559, 30304, 30304,\n",
       "         30304, 30304,  2980,  8720,  8720,  8720, 11791,  8720, 11791,\n",
       "         11791, 24460, 24460, 25546, 25546, 23924, 23924, 23924, 25503],\n",
       "        [24002, 24002, 24002, 30458,  7234,  7234,  7234, 24532, 24532,\n",
       "         31970, 24359, 24359, 24359, 24359, 24359, 22397, 25215, 25215,\n",
       "         20956, 20956, 31304, 31304, 31304, 17272, 16791, 16791, 16791,\n",
       "          3700,  3700,  3700, 25408, 25408, 25408, 29985, 29985, 29985,\n",
       "         27554, 27554, 27554, 27554, 27554, 27554, 27554, 27554, 17856,\n",
       "         17856, 17856,  8448,  8448, 17942, 17942, 17942, 11394,  6256,\n",
       "          6256,  6256,  6256, 28357,  6596,  6596,  6596,  6596, 15738,\n",
       "          2777, 31224, 31224, 31224, 30284, 30284, 30284, 30284,  2272],\n",
       "        [20269,  5486,  5486,  5486,  5486,  5486,  5486,  5486,  5486,\n",
       "         24416,  3316, 19120, 19120, 19120, 19120, 31386, 31386, 31386,\n",
       "         31386, 31386, 31386, 31386, 31386, 17628, 28401, 28401, 28401,\n",
       "         28401, 28401, 28401, 28401, 31876, 31876, 31876, 31876, 31876,\n",
       "         31876, 31876, 31876, 20924, 20924, 20924, 20924, 24799, 24799,\n",
       "         12042, 12042, 12042, 21228, 24799, 21228, 21228, 21228, 28927,\n",
       "         28927, 28927, 28927, 28927, 13477, 13477, 30888, 30888, 16526,\n",
       "         27831, 21674, 21674, 21674, 13416, 13416, 13416,  3120,  3120],\n",
       "        [ 1066,  7228,  7228,  7228,  7228,   529,   529,   529,   529,\n",
       "           529,   529,  4640,  4640, 27396, 27396, 27396, 27396, 27396,\n",
       "           529, 12273, 12273,  8278, 28486, 12092, 12092, 12092, 12092,\n",
       "         12092, 12092, 12092, 12092, 12092, 30640, 30640, 30640, 30640,\n",
       "         13809, 13809, 23164, 23164, 23164, 23164, 23164, 23598, 23598,\n",
       "         23598, 23598, 23541, 23541, 23541, 23541,  2376, 18999, 18999,\n",
       "          3412,  3412,  3412,  3412,  3412,  4030,  2529,  4030,  9867,\n",
       "          9867,  9867,  9867,  9867,  9867,   840,  4519, 29594, 29594],\n",
       "        [ 2453,  2453,  8535,  8535,  8535,  8535,  8535, 21293, 21293,\n",
       "         21293, 21293, 18657, 18657, 18657, 18657, 18657,  4785,  3685,\n",
       "          3685, 13051, 29321, 29321, 29321, 29321, 29321, 20887, 20887,\n",
       "         20887,  8626,  8626,  8626,  8626,  8626, 28782,  1896,  1896,\n",
       "          1896,  1896,  1896,  1896,  4763,  4763,  4763, 15011,  1528,\n",
       "         27520, 27520, 27520, 27520,  1528, 27520, 27520,  5709,  5709,\n",
       "          5709,  5709, 29886, 17387,  8903, 26464,  8903,  8903,  8903,\n",
       "         23782, 27512, 16611, 16611, 22752, 22752, 22752, 20702, 20702]],\n",
       "       dtype=int32), 10.376848, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:50<00:00,  1.75it/s, accuracy=0.253, cost=4.67]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.76it/s, accuracy=0.317, cost=3.97]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.562743, training avg acc 0.184760\n",
      "epoch 1, testing avg loss 4.473169, testing avg acc 0.261835\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:48<00:00,  1.76it/s, accuracy=0.324, cost=3.75]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.85it/s, accuracy=0.344, cost=3.62]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 4.073565, training avg acc 0.297530\n",
      "epoch 2, testing avg loss 3.909445, testing avg acc 0.319642\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:48<00:00,  1.76it/s, accuracy=0.393, cost=3.1] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.83it/s, accuracy=0.36, cost=3.39] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 3.489374, training avg acc 0.355822\n",
      "epoch 3, testing avg loss 3.682845, testing avg acc 0.347560\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:49<00:00,  1.76it/s, accuracy=0.428, cost=2.68]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.81it/s, accuracy=0.392, cost=3.26]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 3.114220, training avg acc 0.398201\n",
      "epoch 4, testing avg loss 3.618922, testing avg acc 0.357220\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:49<00:00,  1.76it/s, accuracy=0.504, cost=2.29]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.82it/s, accuracy=0.371, cost=3.35]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.840606, training avg acc 0.432136\n",
      "epoch 5, testing avg loss 3.605763, testing avg acc 0.359059\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:48<00:00,  1.76it/s, accuracy=0.545, cost=2.07]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.86it/s, accuracy=0.387, cost=3.29]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 2.629314, training avg acc 0.460028\n",
      "epoch 6, testing avg loss 3.645953, testing avg acc 0.364126\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:49<00:00,  1.76it/s, accuracy=0.586, cost=1.84]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.83it/s, accuracy=0.382, cost=3.42]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 2.464055, training avg acc 0.481991\n",
      "epoch 7, testing avg loss 3.699722, testing avg acc 0.359701\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:47<00:00,  1.76it/s, accuracy=0.609, cost=1.67]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.83it/s, accuracy=0.371, cost=3.46]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 2.363693, training avg acc 0.494158\n",
      "epoch 8, testing avg loss 3.744963, testing avg acc 0.360134\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:48<00:00,  1.76it/s, accuracy=0.645, cost=1.55]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.83it/s, accuracy=0.403, cost=3.49]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 2.213604, training avg acc 0.517197\n",
      "epoch 9, testing avg loss 3.858244, testing avg acc 0.355916\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:49<00:00,  1.76it/s, accuracy=0.639, cost=1.51]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.82it/s, accuracy=0.398, cost=3.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 2.126679, training avg acc 0.528660\n",
      "epoch 10, testing avg loss 3.916481, testing avg acc 0.351992\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:49<00:00,  1.76it/s, accuracy=0.654, cost=1.38]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.82it/s, accuracy=0.344, cost=3.67]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 2.049376, training avg acc 0.539353\n",
      "epoch 11, testing avg loss 4.021151, testing avg acc 0.350741\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:48<00:00,  1.76it/s, accuracy=0.685, cost=1.31]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.82it/s, accuracy=0.344, cost=3.81]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.977742, training avg acc 0.550043\n",
      "epoch 12, testing avg loss 4.098323, testing avg acc 0.345367\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:47<00:00,  1.76it/s, accuracy=0.678, cost=1.28]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.81it/s, accuracy=0.366, cost=3.85]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.916311, training avg acc 0.559066\n",
      "epoch 13, testing avg loss 4.176513, testing avg acc 0.347269\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:48<00:00,  1.76it/s, accuracy=0.699, cost=1.18]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.83it/s, accuracy=0.339, cost=4.05]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.856988, training avg acc 0.567954\n",
      "epoch 14, testing avg loss 4.270566, testing avg acc 0.348370\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  52%|█████▏    | 811/1563 [07:39<07:53,  1.59it/s, accuracy=0.587, cost=1.76]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:31<00:00,  1.25it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.06407658"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
